/**
On-Off Android app. Basic game where you must switch off all lights
    Copyright (C) 2010  nineunderground@gmail.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/
package android.luces;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.luces.utils.DeviceValues;
import android.luces.utils.GlobalValues;
import android.luces.utils.Highscore;
import android.luces.utils.Navigation;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class ALuces extends Activity {

	// Sonidos activados / desactivados
	public static	boolean		gameSound		=	true;
	public static	Highscore	gameScores;
	public static	int			language		=	GlobalValues.ENGLISH;
	
	public static String	[]dicIngles;
	public static String	[]dicEspanol;
	public static String	[]dicFrances;
	public static String	[]dicItaliano;
	public static String	[]dicAleman;
	public static String	[]dicFines;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
    	if(savedInstanceState == null){
    	
    		super.onCreate(savedInstanceState);
    		
    		dicIngles		=	getResources().getStringArray(R.array.diccionarioIngles);
    		dicEspanol		=	getResources().getStringArray(R.array.diccionarioEspanol);
    		dicFrances		=	getResources().getStringArray(R.array.diccionarioFrances);
    		dicItaliano		=	getResources().getStringArray(R.array.diccionarioItaliano);
    		dicAleman		=	getResources().getStringArray(R.array.diccionarioAleman);
    		dicFines		=	getResources().getStringArray(R.array.diccionarioFines);
    		
	        gameScores		=	new	Highscore(getBaseContext());
	        
	        //gameScores.deleteAllScores(getBaseContext());
	        
	        // Sin linea de titulo
	        requestWindowFeature(Window.FEATURE_NO_TITLE);
	        
	        // Sin barra de notificaciones
	        Navigation.setFullScreenMode(this);
	        
	        setContentView(R.layout.pruebas_main);
	        
	        cargarEventos();
	        aplicarConfiguracion();
	        setDeviceSpecs();
	        
    	}
        
    }
    
    /**
     * 
     * @param code
     * @return
     */
    public static String[] getDiccionario(int code){
    	
    	String []lang;
    	
    	switch(code){
    	
	    	case GlobalValues.ENGLISH:
	    		
	    		lang	=	dicIngles;
	    		break;
	    		
			case GlobalValues.FINNISH:
			    
				lang	=	dicFines;
			   	break;
			    		
			case GlobalValues.FRENCH:
				
				lang	=	dicFrances;
				break;
			
			case GlobalValues.GERMAN:
							
				lang	=	dicAleman;
				break;
							
			case GlobalValues.ITALIAN:
				
				lang	=	dicItaliano;
				break;
			
			case GlobalValues.SPANISH:
				
				lang	=	dicEspanol;
				break;
				
			default:
		
				lang	=	dicIngles;	
	    	
	    	}
    	
    	return lang;
    	
    }
    
    //**************************************************************************************************************************************
    //
    //									M E N U
    //
    //**************************************************************************************************************************************

	/**
     * Menu de opciones de la pantalla principal. Se lanza al pulsar la tecla del menu
     * 	-	VOLVER		- Volver a la pantalla principal
     * -	PAUSA		- Pausar el juego
     * -	COMENTARIO	- Contiene un comentario de cada foto
     * @return 
     */
    public boolean onCreateOptionsMenu(Menu menu){
		
    	super.onCreateOptionsMenu(menu);
        
    	menu.setQwertyMode(true);
    	
        MenuItem mnu1 = menu.add(0, GlobalValues.MENU_ACERCA_DE, 0, R.string.menu_acerca_de);
    	//MenuItem mnu1 = menu.add(0, GlobalValues.MENU_ACERCA_DE, 0, Navigation.traducir(getDiccionario(ALuces.language), "ACERCA DE"));
        
        mnu1.setAlphabeticShortcut('a');
        //mnu1.setIcon(R.drawable.icono_volver);
        
        return true;
        
	}
    
    /**
     * Definicion del comportamiento de los botones de menu principal
     */
    public boolean onOptionsItemSelected(MenuItem item) {
        
    	switch (item.getItemId()) {
    	
            case GlobalValues.MENU_ACERCA_DE:
                // Se Abre un popup Dialog preguntando si se quiere volver y que se perderan los cambios
            	showDialog(GlobalValues.ALERT_ABOUT_ME);
            	//onCreateDialog(GlobalValues.ALERT_ABOUT_ME);
				//Log.d(this.getClass().getName(), "HAS TOCADO EL BOTON DE VOLVER AL MENU PRINCIPAL \n");
				
            	return true;
            	
            default:
            	super.onOptionsItemSelected(item);
        }

        return false;
    }
    
    /**
     * Modify dinamically every menu item
     */
    public boolean onPrepareOptionsMenu(Menu men){
    
    	MenuItem item	=	men.getItem(GlobalValues.MENU_ACERCA_DE);
    	item.setTitle(Navigation.traducir(getDiccionario(ALuces.language), "ACERCA DE"));
    	
		return true;
    	
    }
    
    //**************************************************************************************************************************************
    //
    //									E V E N T O S     D E     B O T O N E S
    //
    //**************************************************************************************************************************************

    /**
     * Se cargan los eventos de los botones de la pantalla principal
     */
    private void cargarEventos(){
    	
    	// Boton Salir
    	Button endButton = (Button) findViewById(R.id.boton_salir);
    	
    	// Boton Ayuda
    	Button helpButton = (Button) findViewById(R.id.boton_ayuda);
    	
    	// Boton Puntuaciones
    	Button scoreButton = (Button) findViewById(R.id.boton_puntos);
        
    	// Boton Jugar
    	Button startButton = (Button) findViewById(R.id.boton_jugar);
    	
    	// Imagen sonido
    	final ImageView	imagen_sonido	=	(ImageView) findViewById(R.id.imagen_sonido);
    	
    	// Imagen bandera
    	final ImageView	imagen_flag	=	(ImageView) findViewById(R.id.flag);
    	
    	// Moviles tactiles
    	endButton.setOnTouchListener( new View.OnTouchListener() {
			
			public boolean onTouch(View arg0, MotionEvent event) {
				
				if ( event.getAction() == MotionEvent.ACTION_UP ) {
				
					showDialog(GlobalValues.ALERT_EXIT);
					//Log.d(this.getClass().getName(), "HAS TOCADO EL BOTON SALIR \n");
					
				}
				return true;
			}
			
		});

    	// Moviles tactiles
    	helpButton.setOnTouchListener( new View.OnTouchListener() {
			
			public boolean onTouch(View arg0, MotionEvent event) {
				
				if ( event.getAction() == MotionEvent.ACTION_UP ) {
				
					Intent myIntent = new Intent();
					myIntent = Navigation.openActivity(GlobalValues.ACTIVITY_CODE_HELP , myIntent);
					startActivityForResult(myIntent, GlobalValues.ACTIVITY_CODE_HELP);
					
				}
				return true;
			}
				
		});
			
    	// Moviles tactiles
		scoreButton.setOnTouchListener( new View.OnTouchListener() {
			
			public boolean onTouch(View arg0, MotionEvent event) {
				
				if ( event.getAction() == MotionEvent.ACTION_UP ) {
				
					Intent myIntent = new Intent();
					myIntent = Navigation.openActivity(GlobalValues.ACTIVITY_CODE_SCORES , myIntent);
					startActivityForResult(myIntent, GlobalValues.ACTIVITY_CODE_SCORES);
					
				}
				return true;
			}
					
		});
		
		startButton.setOnTouchListener( new View.OnTouchListener() {
			
			public boolean onTouch(View arg0, MotionEvent event) {
				
				if ( event.getAction() == MotionEvent.ACTION_UP ) {
					Intent myIntent = new Intent();
					myIntent = Navigation.openActivity(GlobalValues.ACTIVITY_CODE_GAME , myIntent);
					startActivityForResult(myIntent, GlobalValues.ACTIVITY_CODE_GAME);
				}
				return true;
			}
					
		});
		
		imagen_sonido.setOnTouchListener( new View.OnTouchListener() {
			
			public boolean onTouch(View arg0, MotionEvent event) {
				
				if ( event.getAction() == MotionEvent.ACTION_UP ) {					
					
					//ImageView	sonidoImagen	=	(ImageView) findViewById(R.id.imagen_sonido);
					
					if(ALuces.gameSound){
	            		
						// Se para la musica
	            		ALuces.gameSound = false;
	            		imagen_sonido.setImageResource(R.drawable.sound_switch_icon_no);
	            		
	            	}else{
	            		
	            		// Continua la musica
	            		ALuces.gameSound = true;
	            		imagen_sonido.setImageResource(R.drawable.sound_switch_icon);
	            		
	            	}
					
				}
				return true;
			}
					
		});
		
		// Menu contextual al pulsar y mantener el icono de la bandera
		imagen_flag.setOnCreateContextMenuListener( new OnCreateContextMenuListener() {
			
			/**
			 * Al pulsar una vista salta el evento de menu contextual
			 */
			public void onCreateContextMenu(ContextMenu men, View v,
					ContextMenuInfo inf) {
				
				//this.onCreateContextMenu(men, v, inf);
		    	MenuInflater contMenu	=	getMenuInflater();
		    	contMenu.inflate(R.menu.language_options, men);
				
			}
			
		});
		    
    }
    
    //**************************************************************************************************************************************
    //
    //									M E N U S			C O N T E X T U A L E S
    //
    //**************************************************************************************************************************************
    
    /**
     * Elemento seleccionado del menu contextual
     */
    public boolean onContextItemSelected(MenuItem item){
    	
    	//AdapterContextMenuInfo	info	=	(AdapterContextMenuInfo)item.getMenuInfo();
    	
    	// Imagen bandera
    	final ImageView	imagen_flag	=	(ImageView) findViewById(R.id.flag);
    	
    	switch(item.getItemId()){
    		
    		case R.id.language_en:
    			
    			imagen_flag.setImageResource(R.drawable.uk);
    			ALuces.language	=	GlobalValues.ENGLISH;
    			setContentLanguage(ALuces.language);
    			return true;
    			
    		case R.id.language_es:
    			
    			imagen_flag.setImageResource(R.drawable.spain);
    			ALuces.language	=	GlobalValues.SPANISH;
    			setContentLanguage(ALuces.language);
    			return true;
    			
    		case R.id.language_fr:
    			
    			imagen_flag.setImageResource(R.drawable.france);
    			ALuces.language	=	GlobalValues.FRENCH;
    			setContentLanguage(ALuces.language);
    			// Se reinician las puntuaciones
    			//ALuces.gameScores.deleteAllScores(getBaseContext());
    			//gameScores		=	new	Highscore(getBaseContext());
    			return true;
    		
    		case R.id.language_fi:
    			
    			imagen_flag.setImageResource(R.drawable.finland);
    			ALuces.language	=	GlobalValues.FINNISH;
    			setContentLanguage(ALuces.language);
    			return true;
    		
    		case R.id.language_de:
    			
    			imagen_flag.setImageResource(R.drawable.germany);
    			ALuces.language	=	GlobalValues.GERMAN;
    			setContentLanguage(ALuces.language);
    			return true;
    		
    		case R.id.language_it:
    			
    			imagen_flag.setImageResource(R.drawable.italy);
    			ALuces.language	=	GlobalValues.ITALIAN;
    			setContentLanguage(ALuces.language);
    			return true;
    		
    		default:
    			
    			imagen_flag.setImageResource(R.drawable.spain);
    			ALuces.language	=	GlobalValues.ENGLISH;
    			setContentLanguage(ALuces.language);
    			return true;
    			
    	}
    	
    	
    }
    
    //**************************************************************************************************************************************
    //
    //									C R E A C I O N     D E    A L E R T A S
    //
    //**************************************************************************************************************************************
    
    /**
     * Modify alerts dinamically
     */
    /*
    protected void onPrepareDialog(int id, Dialog d) {
    	
    	AlertDialog		alert = (AlertDialog)d;
    	
    	switch(id){
    	
    		case GlobalValues.ALERT_ABOUT_ME:
    			
    			alert.setTitle( Navigation.traducir(getDiccionario(ALuces.language), "ACERCA DE") );
    			alert.setMessage( Navigation.traducir(getDiccionario(ALuces.language), "ACERCA DE MENSAJE") );
    			
    			break;
    			
    		default:
    			
    			super.onPrepareDialog(id, d);
    	}
    	
    }
    */
    /**
     * Gestiona las distintas alertas que puede recibir el Activity
     */
	protected AlertDialog onCreateDialog(int id) {
        
		super.onCreateDialog(id);
		
		AlertDialog alert;
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		switch(id) {
	        
			case GlobalValues.ALERT_EXIT:
	            
				builder.setTitle(Navigation.traducir(getDiccionario(ALuces.language), "SALIR"));
				builder.setIcon(R.drawable.bombi_encendida);
				builder.setMessage(Navigation.traducir(getDiccionario(ALuces.language), "SALIR_TEXTO"));
				
			    builder.setPositiveButton(Navigation.traducir(getDiccionario(ALuces.language), "Si"), new DialogInterface.OnClickListener() {
			        public void onClick(DialogInterface dialog, int id) {
			        	//Log.d(this.getClass().getName(), "FIN DE JUEGO \n");
			        	removeDialog(GlobalValues.ALERT_EXIT);
			        	ALuces.this.finish();
			        }
			    });
			    
			    builder.setNegativeButton(Navigation.traducir(getDiccionario(ALuces.language), "No"), new DialogInterface.OnClickListener() {
			        public void onClick(DialogInterface dialog, int id) {
			        	//Log.d(this.getClass().getName(), "HAS PULSADO NO \n");
			        	removeDialog(GlobalValues.ALERT_EXIT);
			        }
			    });
				
			    alert = builder.create();
	            
	            break;
	            
			case GlobalValues.ALERT_ABOUT_ME:
				// Navigation.traducir(getDiccionario(ALuces.language), "JUGAR")
				builder.setTitle( Navigation.traducir(getDiccionario(ALuces.language), "ACERCA DE") );
				builder.setIcon(R.drawable.bombi_encendida);
				
				String versionCode	=	"";	
				
				try{
					
					PackageManager pkg	=	getPackageManager();
					PackageInfo	info	=	pkg.getPackageInfo(GlobalValues.NAME_MAIN_PACKAGE, PackageManager.GET_META_DATA);
					versionCode			=	info.versionName;
					
				}catch(NameNotFoundException err){
					
					versionCode	=	"1.0b";
					
				}
				
				builder.setMessage( Navigation.traducir(getDiccionario(ALuces.language), "ACERCA DE MENSAJE").concat("\n\n" + "Version " + versionCode) );
				
			    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			        public void onClick(DialogInterface dialog, int id) {
			        	removeDialog(GlobalValues.ALERT_ABOUT_ME);
			        }
			    });
			    
			    alert = builder.create();
	            
	            break;
	            
	        default:
	            
	        	alert = null;
	        	
        }

        return alert;
        
    }
    
    //**************************************************************************************************************************************
    //
    //									N A V E G A C I O N    D E   A C T I V I T I E S 
    //
    //**************************************************************************************************************************************

	public void onActivityResult(int requestCode, int resultCode, Intent data){
		
		switch (requestCode) {
			
			case GlobalValues.ACTIVITY_CODE_GAME:
		
				Log.d(this.getClass().getName(), "Se recarga de nuevo la opcion del estado del sonido en el icono del altavoz\n");
            	ImageView	sonidoImagen	=	(ImageView) findViewById(R.id.imagen_sonido);
				
            	if(ALuces.gameSound){
            		
					sonidoImagen.setImageResource(R.drawable.sound_switch_icon);
            		
            	}else{
            		
            		sonidoImagen.setImageResource(R.drawable.sound_switch_icon_no);
            		
            	}
				
				switch(resultCode){
				
					case	RESULT_OK:
							
						//Si se ha vuelto de introducir puntuacion se muestra el marcador de puntuaciones
						Log.d(this.getClass().getName(), "Se llama al activity de las puntuaciones\n");
						
						Intent myIntent = new Intent();
						myIntent.putExtra("last_score", data.getIntExtra("last_score", 0) );
						myIntent = Navigation.openActivity(GlobalValues.ACTIVITY_CODE_SCORES , myIntent);
						startActivityForResult(myIntent, GlobalValues.ACTIVITY_CODE_SCORES);
						
						break;
					
				}
				
	            break;
	        
			case GlobalValues.ACTIVITY_CODE_HELP:
				
	            if (resultCode == RESULT_OK) {
	            	
	            	//Log.d(this.getClass().getName(), "Vienes de la ayuda\n");
	                
	            }
	        
	            break;
	            
			case GlobalValues.ACTIVITY_CODE_SCORES:
				
	            if (resultCode == RESULT_OK) {
	                
	            	//Log.d(this.getClass().getName(), "Vienes de las puntuaciones\n");
	            	
	            }
	        	
	            break;
	            
		}
		 
	}
	
	//**************************************************************************************************************************************
    //
    //									T A R E A S				A L				C E R R A R
    //
    //**************************************************************************************************************************************
    
	protected void onDestroy(){
		
		super.onDestroy();
		
		if ( ALuces.this.isFinishing() ){
			
			Log.d(this.getClass().getName(), "Se guardan las preferencias de sonido e idioma\n");
			
			//ALuces.gameSound
			SharedPreferences	pref	=	getBaseContext().getSharedPreferences("LucesPoints", 0);
			SharedPreferences.Editor editor = pref.edit();
	        
			// Sound preferences
	        editor.putBoolean("SOUND", ALuces.gameSound);
	        // Language preferences
	        editor.putInt("LANGUAGE", ALuces.language);
	        
	        editor.commit();
			
	        Log.d(this.getClass().getName(), "Preferencias guardadas\n");
			//musikito.stop();
			
			
		}
		
	}

	//**************************************************************************************************************************************
    //
    //									T R A D U C T I O N
    //
    //**************************************************************************************************************************************

	/**
     * Sets strings according language supplied to this function
     * 
     */
    private void setContentLanguage(int lang) {
		
    	Button		play	=	(Button)findViewById(R.id.boton_jugar);
    	Button		score	=	(Button)findViewById(R.id.boton_puntos);
    	Button		help	=	(Button)findViewById(R.id.boton_ayuda);
    	Button		exit	=	(Button)findViewById(R.id.boton_salir);
    	TextView	sonido	=	(TextView)findViewById(R.id.sonido);
    	TextView	idioma	=	(TextView)findViewById(R.id.idioma);
    	
    	play.setText(Navigation.traducir(getDiccionario(ALuces.language), "JUGAR"));
    	score.setText(Navigation.traducir(getDiccionario(ALuces.language), "PUNTUACIONES"));
    	help.setText(Navigation.traducir(getDiccionario(ALuces.language), "AYUDA"));
    	exit.setText(Navigation.traducir(getDiccionario(ALuces.language), "SALIR"));
    	sonido.setText(Navigation.traducir(getDiccionario(ALuces.language), "SONIDO"));
    	idioma.setText(Navigation.traducir(getDiccionario(ALuces.language), "IDIOMA"));
    	
	}
	
    //**************************************************************************************************************************************
    //
    //									O T R O S
    //
    //**************************************************************************************************************************************

	private void aplicarConfiguracion(){
		
		//ALuces.gameSound
		SharedPreferences	pref	=	getBaseContext().getSharedPreferences("LucesPoints", 0);
		
		ImageView	sonidoImagen	=	(ImageView) findViewById(R.id.imagen_sonido);
		
		// Sound preferences
        boolean gameEffects	=		pref.getBoolean("SOUND", ALuces.gameSound);
		
		if (!gameEffects){
			sonidoImagen.setImageResource(R.drawable.sound_switch_icon_no);
			//sonidoImagen.setBackgroundResource(R.drawable.sound_switch_icon_no);
        }else{
        	sonidoImagen.setImageResource(R.drawable.sound_switch_icon);
        	//sonidoImagen.setBackgroundResource(R.drawable.sound_switch_icon);
        }
		
		// Language preferences
        int gameLanguage	=		pref.getInt("LANGUAGE", ALuces.language);
		final ImageView	imagen_flag	=	(ImageView) findViewById(R.id.flag);
        
        switch(gameLanguage){
		
			case GlobalValues.ENGLISH:
				
				imagen_flag.setImageResource(R.drawable.uk);
				ALuces.language	=	GlobalValues.ENGLISH;
				setContentLanguage(ALuces.language);
				break;
				
			case GlobalValues.SPANISH:
				
				imagen_flag.setImageResource(R.drawable.spain);
				ALuces.language	=	GlobalValues.SPANISH;
				setContentLanguage(ALuces.language);
				break;
				
			case GlobalValues.FRENCH:
				
				imagen_flag.setImageResource(R.drawable.france);
				ALuces.language	=	GlobalValues.FRENCH;
				setContentLanguage(ALuces.language);
				// Se reinician las puntuaciones
				//ALuces.gameScores.deleteAllScores(getBaseContext());
				
				break;
			
			case GlobalValues.FINNISH:
				
				imagen_flag.setImageResource(R.drawable.finland);
				ALuces.language	=	GlobalValues.FINNISH;
				setContentLanguage(ALuces.language);
				break;
			
			case GlobalValues.GERMAN:
				
				imagen_flag.setImageResource(R.drawable.germany);
				ALuces.language	=	GlobalValues.GERMAN;
				setContentLanguage(ALuces.language);
				break;
			
			case GlobalValues.ITALIAN:
				
				imagen_flag.setImageResource(R.drawable.italy);
				ALuces.language	=	GlobalValues.ITALIAN;
				setContentLanguage(ALuces.language);
				break;
			
			default:
				
				imagen_flag.setImageResource(R.drawable.spain);
				ALuces.language	=	GlobalValues.ENGLISH;
				setContentLanguage(ALuces.language);
				break;
				
		}
        
	}
	
	/**
	 * Set global properties reference to device specs
	 */
	private void setDeviceSpecs(){
		
		Display display = getWindowManager().getDefaultDisplay();
		
		DeviceValues.width	= display.getWidth();
		DeviceValues.heigth = display.getHeight();
		
	}

}